<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-20">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <span class="ml-3 text-gray-600">正在加载问卷...</span>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
        <div class="text-red-600 mb-4">
          <svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 18.5c-.77.833.192 2.5 1.732 2.5z" />
          </svg>
        </div>
        <h3 class="text-lg font-medium text-red-800 mb-2">加载失败</h3>
        <p class="text-red-600 mb-4">{{ error }}</p>
        <button @click="loadSurvey" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition-colors">
          重新加载
        </button>
      </div>

      <!-- 已完成状态 -->
      <div v-else-if="hasCompleted" class="bg-green-50 border border-green-200 rounded-lg p-8 text-center">
        <div class="text-green-600 mb-4">
          <svg class="mx-auto h-16 w-16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <h3 class="text-2xl font-bold text-green-800 mb-2">感谢您的参与！</h3>
        <p class="text-green-600 mb-6">您已经完成了这份问卷调查，无需重复提交。</p>
        <button @click="$router.push('/home')" class="bg-green-600 text-white px-6 py-2 rounded hover:bg-green-700 transition-colors">
          返回首页
        </button>
      </div>

      <!-- 问卷内容 -->
      <div v-else-if="survey" class="bg-white rounded-lg shadow-lg overflow-hidden">
        <!-- 问卷标题 -->
        <div class="bg-gradient-to-r from-blue-600 to-purple-600 px-6 py-8 text-white">
          <h1 class="text-2xl font-bold mb-2">{{ survey.title }}</h1>
          <p class="text-blue-100 leading-relaxed">{{ survey.description }}</p>
        </div>

        <!-- 问卷表单 -->
        <form @submit.prevent="submitSurvey" class="p-6 space-y-8">
          <!-- 基本信息部分 -->
          <div v-if="basicInfoQuestions.length > 0" class="border-b border-gray-200 pb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-6">基本信息</h2>
            <div class="space-y-6">
              <div v-for="question in basicInfoQuestions" :key="question.id" class="space-y-3">
                <label class="block text-sm font-medium text-gray-700">
                  {{ question.question_text }}
                  <span v-if="question.is_required" class="text-red-500">*</span>
                </label>
                
                <!-- 文本输入 -->
                <input 
                  v-if="question.question_type === 'basic_info'"
                  v-model="responses[question.id]"
                  type="text"
                  :required="question.is_required"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  :placeholder="'请输入' + question.question_text"
                />
                
                <!-- 单选题 -->
                <div v-else-if="question.question_type === 'multiple_choice'" class="space-y-2">
                  <label v-for="option in question.options" :key="option" class="flex items-center">
                    <input 
                      v-model="responses[question.id]"
                      type="radio"
                      :value="option"
                      :name="`question_${question.id}`"
                      :required="question.is_required"
                      class="mr-2 text-blue-600 focus:ring-blue-500"
                    />
                    <span class="text-sm text-gray-700">{{ option }}</span>
                  </label>
                </div>
              </div>
            </div>
          </div>

          <!-- 评分量表部分 -->
          <div v-if="ratingQuestions.length > 0" class="border-b border-gray-200 pb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-2">核心素养自我评估</h2>
            <p class="text-sm text-gray-600 mb-6">
              请根据您在学习本课程之前（课前）和完成本课程学习之后（课后）的真实情况进行评分。
              <br>（1 = 非常不符合，2 = 不符合，3 = 一般，4 = 符合，5 = 非常符合）
            </p>
            
            <div class="space-y-6">
              <div v-for="question in ratingQuestions" :key="question.id" class="bg-gray-50 p-4 rounded-lg">
                <h3 class="font-medium text-gray-800 mb-4">{{ question.question_text }}</h3>
                
                <!-- 课前课后对比评分 -->
                <div v-if="question.has_before_after" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <!-- 课前评分 -->
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">课前自我评估</label>
                    <div class="flex space-x-2">
                      <label v-for="score in [1, 2, 3, 4, 5]" :key="`before_${score}`" class="flex flex-col items-center">
                        <input 
                          v-model="responses[`${question.id}_before`]"
                          type="radio"
                          :value="score"
                          :name="`question_${question.id}_before`"
                          :required="question.is_required"
                          class="mb-1 text-blue-600 focus:ring-blue-500"
                        />
                        <span class="text-xs text-gray-600">{{ score }}</span>
                      </label>
                    </div>
                  </div>
                  
                  <!-- 课后评分 -->
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">课后自我评估</label>
                    <div class="flex space-x-2">
                      <label v-for="score in [1, 2, 3, 4, 5]" :key="`after_${score}`" class="flex flex-col items-center">
                        <input 
                          v-model="responses[`${question.id}_after`]"
                          type="radio"
                          :value="score"
                          :name="`question_${question.id}_after`"
                          :required="question.is_required"
                          class="mb-1 text-blue-600 focus:ring-blue-500"
                        />
                        <span class="text-xs text-gray-600">{{ score }}</span>
                      </label>
                    </div>
                  </div>
                </div>
                
                <!-- 普通评分 -->
                <div v-else class="flex space-x-4">
                  <label v-for="score in question.options" :key="score" class="flex flex-col items-center">
                    <input 
                      v-model="responses[question.id]"
                      type="radio"
                      :value="score"
                      :name="`question_${question.id}`"
                      :required="question.is_required"
                      class="mb-1 text-blue-600 focus:ring-blue-500"
                    />
                    <span class="text-xs text-gray-600">{{ score }}</span>
                  </label>
                </div>
              </div>
            </div>
          </div>

          <!-- 开放性问题部分 -->
          <div v-if="openEndedQuestions.length > 0" class="pb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-6">开放性问题</h2>
            <div class="space-y-6">
              <div v-for="question in openEndedQuestions" :key="question.id" class="space-y-3">
                <label class="block text-sm font-medium text-gray-700">
                  {{ question.question_text }}
                  <span v-if="question.is_required" class="text-red-500">*</span>
                </label>
                <textarea 
                  v-model="responses[question.id]"
                  :required="question.is_required"
                  rows="4"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-vertical"
                  :placeholder="'请详细回答...'"
                ></textarea>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-center pt-6">
            <button 
              type="submit"
              :disabled="submitting"
              class="bg-gradient-to-r from-blue-600 to-purple-600 text-white px-8 py-3 rounded-lg font-medium hover:from-blue-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
            >
              <span v-if="submitting" class="flex items-center">
                <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                提交中...
              </span>
              <span v-else>提交问卷</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 从环境变量获取 API 基础地址
const API_BASE_URL = `http://${import.meta.env.VITE_BACKEND_HOST}:${import.meta.env.VITE_BACKEND_PORT}`

// 响应式数据
const loading = ref(true)
const error = ref('')
const survey = ref<any>(null)
const responses = ref<Record<string, any>>({})
const submitting = ref(false)
const hasCompleted = ref(false)
const startTime = ref(Date.now())

// 计算属性：按类型分组问题
const basicInfoQuestions = computed(() => {
  if (!survey.value?.questions) return []
  return survey.value.questions.filter((q: any) => 
    q.question_type === 'basic_info' || q.question_type === 'multiple_choice'
  )
})

const ratingQuestions = computed(() => {
  if (!survey.value?.questions) return []
  return survey.value.questions.filter((q: any) => q.question_type === 'rating_scale')
})

const openEndedQuestions = computed(() => {
  if (!survey.value?.questions) return []
  return survey.value.questions.filter((q: any) => q.question_type === 'open_ended')
})

// 加载问卷
const loadSurvey = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const response = await fetch(`${API_BASE_URL}/api/survey/random`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      survey.value = result.data
      startTime.value = Date.now()
      
      // 检查是否已经完成过这个问卷
      await checkCompletion()
    } else {
      throw new Error(result.message || '获取问卷失败')
    }
  } catch (err: any) {
    console.error('加载问卷失败:', err)
    error.value = err.message || '网络连接失败，请检查网络设置'
  } finally {
    loading.value = false
  }
}

// 检查是否已完成问卷
const checkCompletion = async () => {
  if (!survey.value || !authStore.user?.id) return
  
  try {
    const response = await fetch(
      `${API_BASE_URL}/api/survey/check/${authStore.user.id}/${survey.value.id}`,
      {
        headers: {
          'Authorization': `Bearer ${authStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        hasCompleted.value = result.data.hasCompleted
      }
    }
  } catch (err) {
    console.warn('检查完成状态失败:', err)
  }
}

// 提交问卷
const submitSurvey = async () => {
  if (!survey.value || !authStore.user?.id) return
  
  try {
    submitting.value = true
    
    // 计算完成时间（秒）
    const completionTime = Math.round((Date.now() - startTime.value) / 1000)
    
    const response = await fetch(`${API_BASE_URL}/api/survey/submit`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        studentId: authStore.user.id,
        surveyId: survey.value.id,
        responses: responses.value,
        completionTime
      })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      // 提交成功，显示感谢页面
      hasCompleted.value = true
      
      // 可选：显示成功提示
      alert('问卷提交成功！感谢您的参与。')
    } else {
      throw new Error(result.message || '提交失败')
    }
  } catch (err: any) {
    console.error('提交问卷失败:', err)
    alert(`提交失败：${err.message}`)
  } finally {
    submitting.value = false
  }
}

// 组件挂载时加载问卷
onMounted(() => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  loadSurvey()
})
</script>

<style scoped>
/* 自定义样式 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>